package com.ehome.poct.terminal.aspect;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.ehome.context.thread.UserThreadLocal;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author baisi
 * 日志输出
 */
@Component
@Aspect
@Slf4j
public class WebLogAspect {

    private static final String USER_PHONE_DEFUALT="";

    @Pointcut("@annotation(Weblog)")
    //@Pointcut("@execution(public * com.ehome.*.controller.*.*(..))")
    public void  weblog() {

    }


    @Around("weblog()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        String userPhone=USER_PHONE_DEFUALT;
        try{
            //获取请求地址
            HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String url = request.getRequestURL().toString();
            //String methName = joinPoint.getSignature().toShortString();
            Object[] arg = joinPoint.getArgs();
            //用户信息可为空
            if(Objects.nonNull(UserThreadLocal.getUser())){
                // userPhone= UserThreadLocal.getUser().getMobilePhone();
                userPhone = UserThreadLocal.getUser().getId();
            }
            String startTime = LocalDateTimeUtil.format(LocalDateTimeUtil.now(),DatePattern.NORM_DATETIME_MS_PATTERN);
            if(log.isInfoEnabled()){
                log.info("请求时间 : 【{}】, 用户 : 【{}】, url : 【{}】 request : 【{}】",startTime,userPhone,url,arg);
            }
        }catch(Exception ex){
            //日志输出失败，不影响业务
            log.warn("log print error",ex);
        }
        //执行业务
        Object result = joinPoint.proceed();
        try{
            String endTime = LocalDateTimeUtil.format(LocalDateTimeUtil.now(),DatePattern.NORM_DATETIME_MS_PATTERN);
            if(log.isInfoEnabled()){
                log.info("返回时间 : 【{}】, 用户 : 【{}】, result : 【{}】",endTime,userPhone,new Gson().toJson(result));
            }
        }catch(Exception ex){
            //日志输出失败，不影响业务
            log.warn("log print error",ex);
        }
        return result;
    }

}
